//
//  TotalStatisticsViewController.m
//  OA
//
//  Created by yy on 17/7/4.
//  Copyright © 2017年 yy. All rights reserved.
//

#import "TotalStatisticsViewController.h"
#import "TotalStatisticHeaderView.h"
#import "TotalStatisticsTableViewCell.h"
@interface TotalStatisticsViewController ()<UITableViewDataSource,UITableViewDelegate,RegionDelegate>
@property (weak, nonatomic) IBOutlet UILabel *imgL;
@property (weak, nonatomic) IBOutlet UIImageView *img;
@property (weak, nonatomic) IBOutlet UILabel *titleL;
@property (weak, nonatomic) IBOutlet UILabel *kqL;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *monthChooseBtn;//月份选择
@property (nonatomic,strong) NSMutableArray *arrTypeOfheader;//
@property (nonatomic,strong) NSMutableArray *arrTitleOfheader;//title
@property (nonatomic,strong) NSMutableArray *arrDetailOfheader;//数据

@property (nonatomic,strong) StatisticsModel  *statisticsModel;
@property (nonatomic,strong) NSString *beginworktime;//入职日期
@property (nonatomic,strong) NSMutableArray *arrOfWorkMouth;//入职日期
@property (nonatomic,strong) BasisChooseRegionView *dateMonthView;
@end

@implementation TotalStatisticsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"统计";
    if (_isMy == YES) {//个人统计
        Y_tableViewMj_header([weakSelf initOfDataSouce:[ToolOfBasic nowTime]];)
        [self initOfDataSouce:[ToolOfBasic nowTime]];
    }else{//以用户权限来确定统计界面情况
        Y_tableViewMj_header([weakSelf initOfDataSouce:[ToolOfBasic nowTime]];)
        [self initOfDataSouce:[ToolOfBasic nowTime]];
    }
}

-(void)viewWillAppear: (BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tabBarController.tabBar setHidden:YES];
}

#pragma mark —————— 某月数据
- (void)initOfDataSouce:(NSString *)dateStr{
    
    _arrTitleOfheader = [NSMutableArray array];
    _arrDetailOfheader = [NSMutableArray array];
    _arrTypeOfheader = [NSMutableArray array];//伸缩类型
    
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    [parm setObject:dateStr forKey:@"datenumber"];
    [parm setObject:@"1" forKey:@"type"];//类型（0：单位；1个人）
    [[ToolOfNetWork sharedTools]YrequestURL:oa_getStatisticsOfMonth withParams:parm finished:^(id responsObject, NSError *error) {
        Y_headerEndRefreshing;
        if (_Success) {
            
            _statisticsModel = [StatisticsModel objectWithKeyValues:responsObject[@"data"]];
             [self initializeUserInterface];
             [self addMoreDataOfNoFixed];
             [_monthChooseBtn setTitle:[dateStr substringToIndex:7] forState:UIControlStateNormal];
            [_dateMonthView removeFromSuperview];
            
        }else{
            Y_MBP_ErrMessage
        }
    }];
}

- (void)addMoreDataOfNoFixed{
    
    _arrTitleOfheader =  [NSMutableArray array];
//    if (_statisticsModel.attendanceList.count>0) {
//        [_arrDetailOfheader addObject:_statisticsModel.attendanceList];
//        [_arrTitleOfheader addObject:@"出勤天数"];
//    }
//    if (_statisticsModel.restList.count>0) {
//        [_arrDetailOfheader addObject:_statisticsModel.restList];
//        [_arrTitleOfheader addObject:@"休息天数"];
//    }
//    if (_statisticsModel.lateList.count>0) {
//         [_arrDetailOfheader addObject:_statisticsModel.lateList];
//        [_arrTitleOfheader addObject:@"迟到"];
//    }
//    if (_statisticsModel.earlyList.count>0) {
//        [_arrDetailOfheader addObject:_statisticsModel.earlyList];
//        [_arrTitleOfheader addObject:@"早退"];
//    }
//    if (_statisticsModel.qkList.count>0){
//          [_arrDetailOfheader addObject:_statisticsModel.qkList];
//        [_arrTitleOfheader addObject:@"缺卡"];
//    }
//    if (_statisticsModel.kgList.count>0) {
//        [_arrDetailOfheader addObject:_statisticsModel.kgList];
//        [_arrTitleOfheader addObject:@"旷工"];
//    }
    
    
        [_arrDetailOfheader addObject:_statisticsModel.attendanceList];
        [_arrTitleOfheader addObject:@"出勤天数"];
    
        [_arrDetailOfheader addObject:_statisticsModel.restList];
        [_arrTitleOfheader addObject:@"休息天数"];
   
        [_arrDetailOfheader addObject:_statisticsModel.lateList];
        [_arrTitleOfheader addObject:@"迟到"];
    
        [_arrDetailOfheader addObject:_statisticsModel.earlyList];
        [_arrTitleOfheader addObject:@"早退"];
   
   
        [_arrDetailOfheader addObject:_statisticsModel.qkList];
        [_arrTitleOfheader addObject:@"缺卡"];
    
        [_arrDetailOfheader addObject:_statisticsModel.kgList];
        [_arrTitleOfheader addObject:@"旷工"];
    
    if (_statisticsModel.qjList.count>0) {
        [_arrDetailOfheader addObject:_statisticsModel.wqList];
        [_arrTitleOfheader addObject:@"外勤"];
    }
    if (_statisticsModel.qjList.count>0) {
           [_arrTitleOfheader addObject:@"请假"];
           [_arrDetailOfheader addObject:_statisticsModel.qjList];
    }
    if (_statisticsModel.jbList.count>0) {
        [_arrTitleOfheader addObject:@"加班"];
        [_arrDetailOfheader addObject:_statisticsModel.jbList];
    }
    if (_statisticsModel.ccList.count>0) {
        [_arrTitleOfheader addObject:@"出差"];
        [_arrDetailOfheader addObject:_statisticsModel.ccList];
    }
    for (int i = 0;  i < _arrDetailOfheader.count; i++) {
        [_arrTypeOfheader addObject:@"0"];
    }
    [_tableView reloadData];
}



- (void)initializeUserInterface{
     _imgL.text = _statisticsModel.username.length>2?[_statisticsModel.username substringWithRange:NSMakeRange(_statisticsModel.username.length-2, 2)]:_statisticsModel.username;
    _titleL.text = _statisticsModel.username;
    _kqL.text = _statisticsModel.team;
    _beginworktime = _statisticsModel.beginworktime;
    [self getWorkMouthArr:_beginworktime];//月份

    UILabel *footerL = [[UILabel alloc]init];
    footerL.text = [NSString stringWithFormat:@"本月平均工时：%@分钟",[[ToolOfBasic timeFormatted:[_statisticsModel.num_avg intValue]] stringByReplacingOccurrencesOfString:@":" withString:@"小时"]];
    
    
    footerL.textAlignment = NSTextAlignmentCenter;
    footerL.textColor = [UIColor grayColor];
    footerL.font = [UIFont systemFontOfSize:15];
    footerL.bounds = CGRectMake(0, 0, Y_mainW, 30);
    footerL.center = CGPointMake(Y_mainW*0.5, 10);
    _tableView.tableFooterView = footerL;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)getWorkMouthArr:(NSString *)beginworktimeStr{
    
//    月份
    _arrOfWorkMouth = [NSMutableArray array];
   [_arrOfWorkMouth insertObject:[_beginworktime substringToIndex:7] atIndex:0];//当月
    for (int i = 0; ; i ++) {
        if (![[_beginworktime substringToIndex:7] isEqualToString: [[ToolOfBasic dayInTheFollowingMonthStr:[_arrOfWorkMouth firstObject]] substringToIndex:7] ] &&  ![[[ToolOfBasic nowTime]substringToIndex:7] isEqualToString:[_arrOfWorkMouth firstObject]]) {//判断月份相同
            [_arrOfWorkMouth insertObject: [[ToolOfBasic dayInTheFollowingMonthStr:[_arrOfWorkMouth firstObject]] substringToIndex:7] atIndex:0];//月份添加
        }else{
            break;
        }
    }
 
    
   
}
#pragma mark —————— 选择月份
- (IBAction)mouthChooseAction:(UIButton *)sender {

    [self.view addSubview:self.dateMonthView];
}
#pragma mark —————— 选择日历
- (IBAction)calendarBtnAction:(UIButton *)sender {
     NSLog(@"打卡月历");
    StatisticsViewController *statisticsVc = VCInSB(@"StatisticsViewController", @"ThirdViewControllers");
    [self.navigationController pushViewController:statisticsVc animated:YES];
}

#pragma mark —————— 
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _arrTitleOfheader.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([_arrTypeOfheader[section] isEqualToString:@"0"]) {
        return 0;
    }else{
        NSArray *arr = [NSArray arrayWithArray:_arrDetailOfheader[section]];
        return arr.count;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [self headrViewOfSection:section];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}
- (UIView *)headrViewOfSection:(NSInteger)section{
   UIView *tableHeader = (UIView *)[[[NSBundle mainBundle]loadNibNamed:@"TotalStatisticHeaderView" owner:self options:nil]objectAtIndex:0];

    for (id obj in tableHeader.subviews) {
        if ([obj isKindOfClass:[UIButton class]]) {
            UIButton *scalingBtn = obj;
            scalingBtn.tag = TAG_BTN_B + section;
            [scalingBtn addTarget:self action:@selector(scalingBtnAction:)  forControlEvents:UIControlEventTouchUpInside];
            scalingBtn.selected = [_arrTypeOfheader[section] boolValue];
        }
        if ([obj isKindOfClass:[UILabel class]]) {
            UILabel *lab = obj;
            if (lab.tag==200) {//200title 300detail
                lab.text = _arrTitleOfheader[section];
            }else{
//              lab.text = [NSString stringWithFormat:@"header%ld",(long)section];
                 NSArray *arr = [NSArray arrayWithArray:_arrDetailOfheader[section]];
                lab.text = [NSString stringWithFormat:@"%lu",(unsigned long)arr.count];
            }
        }
    }
    return tableHeader;
    
}
- (void)scalingBtnAction:(UIButton *)sender{

    sender.selected = !sender.selected;
    NSMutableArray *newArray = [_arrTypeOfheader mutableCopy];
    [newArray replaceObjectAtIndex:sender.tag-TAG_BTN_B withObject:sender.selected?@"1":@"0"];
    _arrTypeOfheader = newArray;
    [self.tableView reloadData];
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TotalStatisticsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TotalStatisticsTableViewCell"];
    if (!cell) {
        cell = [[TotalStatisticsTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TotalStatisticsTableViewCell"];
    }
    NSArray *arrOfOneSection = [NSArray arrayWithArray:_arrDetailOfheader[indexPath.section]];
//    if ([_arrTitleOfheader[indexPath.section] isEqualToString:@"请假"]||[_arrTitleOfheader[indexPath.section] isEqualToString:@"加班"]||[_arrTitleOfheader[indexPath.section] isEqualToString:@"出差"]||[_arrTitleOfheader[indexPath.section] isEqualToString:@"外勤"]) {
//        cell.dicOfQj = arrOfOneSection[indexPath.row];
//    }else  if([_arrTitleOfheader[indexPath.section] isEqualToString:@"迟到"]||[_arrTitleOfheader[indexPath.section] isEqualToString:@"早退"]){
//        cell.dicOfCd = arrOfOneSection[indexPath.row];
//    }else{
//       cell.dic = arrOfOneSection[indexPath.row];
//    }
    if ([_arrTitleOfheader[indexPath.section] isEqualToString:@"请假"]||[_arrTitleOfheader[indexPath.section] isEqualToString:@"加班"]||[_arrTitleOfheader[indexPath.section] isEqualToString:@"出差"]) {
        cell.dicOfQj = arrOfOneSection[indexPath.row];
    }else  if([_arrTitleOfheader[indexPath.section] isEqualToString:@"迟到"]||[_arrTitleOfheader[indexPath.section] isEqualToString:@"早退"]){
        cell.dicOfCd = arrOfOneSection[indexPath.row];
    }else{
        cell.dic = arrOfOneSection[indexPath.row];
    }

    
    
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //日历
    
    StatisticsViewController *statisticsVc = VCInSB(@"StatisticsViewController", @"ThirdViewControllers");
    NSArray *arrOfOneSection = [NSArray arrayWithArray:_arrDetailOfheader[indexPath.section]];
    
    NSString *dateStr = [NSString stringWithFormat:@"%@",arrOfOneSection[indexPath.row][@"datenumber"]];
    NSString *begintimeStr = [NSString stringWithFormat:@"%@", arrOfOneSection[indexPath.row][@"begintime"]];
//    if ([self isBlankString:dateStr]) {
    if (dateStr.length<begintimeStr.length) {
        statisticsVc.dateStr = [begintimeStr substringToIndex:10];
    }else{
        statisticsVc.dateStr = dateStr;
    }
    [self.navigationController pushViewController:statisticsVc animated:YES];
}
 
#pragma mark —————— 月份选择

- (BasisChooseRegionView *)dateMonthView{
    if (!_dateMonthView) {
        _dateMonthView = [[[NSBundle mainBundle]loadNibNamed:@"BasisChooseRegionView" owner:self options:nil]objectAtIndex:0];
        _dateMonthView.frame = CGRectMake(30, 30, Y_mainW-60, 280);
        _dateMonthView.center = self.view.center;
        _dateMonthView.layer.cornerRadius = 20;
        _dateMonthView.layer.borderWidth = 0.2;
        _dateMonthView.delegateOfRegion = self;
        _dateMonthView.arrOfData = _arrOfWorkMouth;
        
    }
    return _dateMonthView;
}

- (NSString *)regionOfdidSelect:(NSString *)strOfArea{
    
    [self initOfDataSouce:[NSString stringWithFormat:@"%@-01",strOfArea]];//选择了某月
    return strOfArea;
    
}
- (void)removeRegionView{
    [_dateMonthView removeFromSuperview];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [_dateMonthView removeFromSuperview];
}
@end
